package com.yb.client.config;

import com.yb.client.bean.LoginSuccessResult;
import com.yb.core.model.XczxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/17 12:30
 * FileName: OauthLoginConfig
 * Description:
 */

@Configuration
@EnableWebSecurity
public class Oauth2ClientLoginConfig {

    @Autowired
    RestTemplate restTemplate;

    @Bean
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize

                        .antMatchers("/login.html").permitAll()
                        .anyRequest().authenticated()
                );

        http.oauth2Login(loginConfigurer -> {
            loginConfigurer.loginPage("/login.html");
            loginConfigurer.successHandler(new AuthenticationSuccessHandler() {
                @Override
                public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                    OAuth2AuthenticationToken authenticationToken= (OAuth2AuthenticationToken) authentication;


                    if(authenticationToken.getPrincipal() instanceof DefaultOAuth2User){
                        DefaultOidcUser principal = (DefaultOidcUser) authenticationToken.getPrincipal();
                        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                        HttpSession session = request.getSession(false);
                        SavedRequest savedRequest= (session != null) ? (SavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST") : null;
                        LoginSuccessResult result = new LoginSuccessResult();
                        result.setToken(principal.getIdToken().getTokenValue());
                        result.setRedirectUrl(savedRequest.getRedirectUrl());
                        response.getWriter().write(XczxResult.success(result).toJSON());
                    }

                }
            }
            );
        });
        return http.build();
    }
}
